using System.Threading;
using System.Windows.Input;
using CuteConsole.Mvvm;

namespace CuteConsole.ConsoleElements
{
  internal abstract class InputElement<T> : ViewModelBase
  {
    private T _input;
    private bool _isDone;
    private ICommand _doneCommand;
    private readonly ManualResetEvent _manualResetEvent = new ManualResetEvent(false);

    public T Input
    {
      get { return _input; }
      set 
      {
        if (Equals(_input, value)) return;
        _input = value;
        OnPropertyChanged("Input");
      }
    }
    public string Request { get; private set; }
    public bool IsDone
    {
      get { return _isDone; }
      set
      {
        if (_isDone == value) return;
        _isDone = value;
        OnPropertyChanged("IsDone");
      }
    }
    public ICommand DoneCommand
    {
      get
      {
        if (_doneCommand == null)
        {
          _doneCommand = new RelayCommand(param => Done());
        }
        return _doneCommand;
      }
    }

    protected InputElement(string request)
    {
      Request = request;
    }

    public T WaitInput()
    {
      _manualResetEvent.WaitOne();
      return _input;
    }

    protected bool Done()
    {
      IsDone = true;
      return _manualResetEvent.Set();
    }
  }
}